package com.locationtracker.plus.app.util.gsonCoverter;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;

import java.io.IOException;

import me.hgj.jetpackmvvm.network.ServiceException;
import okhttp3.ResponseBody;
import retrofit2.Converter;

final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String json = value.string();
        try {
            JsonObject jo = gson.fromJson(json, JsonObject.class);
            if (jo.has("success") && jo.get("success").getAsInt() != 200) {
                throw new ServiceException(jo.get("success").getAsInt(), jo.get("err").getAsString(), json);
            }
            return adapter.fromJson(json);
        } finally {
            value.close();
        }
    }
}
